package main

import (
	"fmt"
	"github.com/boltdb/bolt"
	"log"
	"os"
	"strconv"
	"time"
)

func main() {
	// Open the my.db data file in your current directory.
	// It will be created if it doesn't exist.
	db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 30 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	s, err := strconv.Atoi(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	c, err := strconv.Atoi(os.Args[2])
	if err != nil {
		log.Fatal(err)
	}
	log.Println("count", s, c)
	read(db)
	//write(db, s, c+s)
}

func write(db *bolt.DB, start, length int) {
	err := db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("MyBucket"))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
	err = db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("MyBucket"))
		for i := start; i < length; i++ {
			k := fmt.Sprintf("%v", i)
			err := b.Put([]byte(k), []byte(k))
			if err != nil {
				return err
			}
		}
		return nil
	})

}

func read(db *bolt.DB) {
	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("MyBucket"))
		c := b.Cursor()
		var i int = 0
		for k, _ := c.First(); k != nil; k, _ = c.Next() {
			i += 1
		}
		log.Println(i)
		return nil
	})

}
